package com.dyp.content_negotiation.ctr;

import com.dyp.content_negotiation.model.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserCtr {
    @GetMapping(produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_YAML_VALUE,
                            MediaType.TEXT_PLAIN_VALUE})
    public User getUser() {
        return new User("John", "xi'an"); // 自动根据Accept头返回JSON/XML
    }

    @GetMapping(value="/lists", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE,
            MediaType.APPLICATION_YAML_VALUE, MediaType.TEXT_PLAIN_VALUE, "text/csv"})
    public List<User> getUsers() {
        List<User> users = new ArrayList<>();
        User user0 =new  User("John", "xi'an");
        User user1 = new User("John", "xi'an");
        users.add(user0);
        users.add(user1);
        return users; // 自动根据Accept头返回JSON/XML
    }

    @GetMapping("/custom")
    public ResponseEntity<User> getUserCustom(HttpServletRequest request) {
        User user = new User("John", "custom");
        if (request.getHeader("Accept").contains("xml"))  {
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_XML)
                    .body(user);
        } else {
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(user);
        }
    }

    @GetMapping(value = "/user/res",produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<User> getUserAuto(HttpServletRequest request) {
        User user = new User("John", "custom");
        return ResponseEntity.ok()
                .body(user);
    }
}
